'use strict';

angular.module('backOffice.frontendUser.controllers', []).
    controller('frontendUserCtrl', ['$scope', '$location', '$http', 'portraitService', function ($scope, $location, $http, portraitService) {

        $scope.portraitList = portraitService.getPortraitService();

        $scope.currentPage = 1;
        $scope.totalPage = 10;
        $scope.pageSize = 30;
        $scope.pages = [];


        function datePicker(id) {
            function d(id) {
                var self = this;
                $(id).datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    forceParse: false
                }).on('changeDate', function (e) {
                    self.date = e.date;
                }).on('show', function (e) {
                    $(".datepicker.datepicker-dropdown.dropdown-menu").css("z-index", "10000");
                });
            }

            d.prototype.getValue = function () {
                if (this.date == null) {
                    return null;
                }
                return this.date.setHours(0, 0, 0, 0)
            }
            var date = new d(id);
            return date;
        }

        $scope.bDate = datePicker('#birthday');

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            if ($scope.search != null) {
                //var community = $scope.search.selectedCommunity == null?null:$scope.search.selectedCommunity.objId;
                var community = $("#community_select")[0].dataset.cId == null ? 'all' : $("#community_select")[0].dataset.cId;

                searchFrontendUser(community, $scope.search.mobilePhone, $scope.search.nickName, $scope.search.isVUser, $scope.search.isTalent, $scope.userRole, page)
            }else{
                searchFrontendUser(null, null, null, null,null, null,page)
            }
        };

        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getAllCommunity', {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (result) {
            //$scope.search.selectedCommunity = "";
            $scope.communityList = result.data;
            //var setIn = setInterval(function(){
                if($scope.communityList){
                    //clearInterval(setIn);
                    var selectList = [];
                    $scope.communityList.forEach(function(item){
                        var a = {};
                        a.name = item.communityName;
                        a.id = item.objId;
                        selectList.push(a);
                    });
                    new select({data:selectList,id:"community_select"});
                }
            //},500);
        }).error(function () {
        });

        /**
         * 弹出框，修改用户信息
         * @param user
         */
        $scope.saveUserInfo = function (user) {
            console.log(user);
            var tempUser = {
                community: $scope.community,
                nickName: user.nickName,
                roomUnit: user.roomUnit,
                roomNumber: user.roomNumber,
                gender: user.gender,
                remark:user.remark
            };
            if ($scope.bDate.getValue() != null)
                tempUser.birthDate = $scope.bDate.getValue();

            console.log($scope.community);
            console.log(tempUser);
            $http.put('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/updateUser/' + user.objId, tempUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#userDetail').modal('hide');

                if ($scope.search != null) {
                    var community = $("#community_select")[0].dataset.cId == null ? 'all' : $("#community_select")[0].dataset.cId;
                    searchFrontendUser(community, $scope.search.mobilePhone, $scope.search.nickName, $scope.search.isVUser, $scope.search.isTalent, $scope.userRole);
                }else{
                    searchFrontendUser(null, null, null, null, null, null);
                }

            }).error(function () {
            });
        }

        function searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent,userRole) {

            $scope.showErrorForQueryCondition = false;
            $('#errorMsg').html('');

            var communityObjId = $("#community_select")[0].dataset.cId == null ? 'all' : $("#community_select")[0].dataset.cId;

            if (communityObjId == null) {
                //$scope.showErrorForQueryCondition = true;
                //$('#errorMsg').html('请选择小区!');
                //return;

                communityObjId = 'all';
            }
            if (mobilePhone == null || mobilePhone == '') {
                mobilePhone = 'all';
            }
            if (nickName == null || nickName == '') {
                nickName = 'all';
            }
            if (isVUser == null || isVUser == '') {
                isVUser = 'all';
            }
            if (isTalent == null || isTalent == '') {
                isTalent = 'all';
            }
            if (userRole == null || userRole == '') {
                userRole = 'all';
            }

            var startDate = '';
            if ($("#startDate").val() == null || $("#startDate").val() == '') {
                startDate = '2000-01-01'
            } else {
                startDate = $("#startDate").val();
            }

            var endDate = '';
            if ($("#endDate").val() == null || $("#endDate").val() == '') {
                endDate = '2100-01-01'
            } else {
                endDate = $("#endDate").val();
            }

            if (startDate > endDate) {
                $scope.showErrorForQueryCondition = true;
                $('#errorMsg').html('起始日期不能大于终止日期!');
                return;
            }

            var pageSize = 20;
            var startRowNo = ($scope.currentPage - 1) * pageSize;

            //找出该小区的所有用户
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/searchFrontendUser/' + communityObjId + '/' + mobilePhone + '/' + nickName + '/' + isVUser + '/' + isTalent +'/'+ userRole + '/' + startDate + '/' + endDate + '/' + startRowNo + '/' + pageSize, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.userList = result.data;
                $scope.totalPage = result.data.totalNum;
                $scope.userList.items.forEach(function (elem) {
                    if (elem.mobilePhone != null && elem.mobilePhone != '') {
                        elem.source = '手机';
                    } else {
                        if (elem.wechatId != null && elem.wechatId != '') {
                            if (elem.wechatId.substring(0, 2) == 'ow') {
                                elem.source = '微信';
                            } else {
                                elem.source = 'QQ';
                            }
                        } else {
                            elem.source = '未知';
                        }
                    }
                });
            }).error(function () {
            });
        }


        /**
         * 查询小区的所有用户
         * @param communityObjId
         * @param mobilePhone
         * @param nickName
         */
        $scope.searchUser = function (communityObjId, mobilePhone, nickName, isVUser, isTalent,userRole) {
            searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent,userRole, 1);
        };

        /**
         * 下拉框选择小区
         */
        $scope.selectCommunity = function () {
            $scope.showErrorForQueryCondition = false;
        }

        /**
         * 获取用户详细信息
         * @param user
         */
        $scope.goDetail = function (user) {
            $scope.communityLabelList = $scope.communityList;
            $scope.community = user.community.objId;
            $('#userDetail').modal('show');
            $scope.userDetail = user;


        }

        /**
         * 弹出黑白操作框
         * @param user
         */
        $scope.blackListConfig = function (user, type) {
            $('#user_modal').modal('show');
            $scope.toBeBlackListUserObjId = user.objId;
            $scope.toBeBlackListUserNickName = user.nickName;
            $("#nickName").prop('disabled', false);

            //拉黑用户，需要显示原因
            if (type == 0) {
                $scope.popupTitle = "把该用户拉黑...";
                $('#reasonInput').show();
                $scope.toBeBlackListUserFrozen = true;
                $scope.toBeBlackListUserReason = null;
                $('#saveButton').text('设置黑名单');
            }
            else {
                $scope.popupTitle = "把该用户拉白...";
                $('#reasonInput').hide();
                $scope.toBeBlackListUserFrozen = false;
                $scope.toBeBlackListUserReason = ' ';
                $('#saveButton').text('设置白名单');
            }
        };

        /**
         * v用户审核
         */

        $scope.validateVUserDetails = function (user, messageTitle, authenticationStatus) {
            $('#validateVUserDetails').modal('show');
            var roomUnit = user.roomUnit;
            var roomNumber = user.roomNumber;
            $('input:radio[name=validateVUserDetails_gender]:checked').prop('checked', false);
            //$("#validateVUserDetails_gender_male").removeAttr('checked');
            if (user.gender) {
                var selector = "input:radio[name=validateVUserDetails_gender]"
                user.gender === "男" || user.gender === "male" ? $(selector + ':nth(0)').prop('checked', true) : $(selector + ':nth(1)').prop('checked', true);
            }
            $('#validateVUserDetails_form').validate({
                submitHandler: function (form) {
                    //var gender=$(form).find('input:radio[name=validateVUserDetails_gender]:checked').val();
                    //var apartmentDetails=$(form).find('#validateVUserDetails_apartmentDetails').val();
                    //var roomUnit=$(form).find('#validateVUserDetails_roomUnit').val();
                    //var roomNumber=$(form).find('#validateVUserDetails_roomNumber').val();

                    if (user.roomUnit !== roomUnit || user.roomNumber !== roomNumber) {
                        $scope.saveUserInfo(user)
                    }
                    $scope.setOrCancelVUser(user, messageTitle, authenticationStatus);
                    $('#validateVUserDetails').modal('hide');

                },
                rules: {
                    "validateVUserDetails_gender": "required",
                    "validateVUserDetails_roomUnit": "required",
                    "validateVUserDetails_roomNumber": "required"
                },
                messages: {
                    "validateVUserDetails_gender": "不能为空",
                    "validateVUserDetails_roomUnit": "不能为空",
                    "validateVUserDetails_roomNumber": "不能为空"
                }
            });
            $scope.userDetail = user;
            var tempValue = {
                authenticationStatus: authenticationStatus
            }
        }

        /**
         * 把用户设置为VUser，或者取消VUser
         */
        $scope.setOrCancelVUser = function (user, messageTitle, authenticationStatus) {
            var tempValue = {
                authenticationStatus: authenticationStatus
            }
            bootbox.confirm(messageTitle, function (result) {
                if (result == true) {
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelVUser/' + user.objId + '/' + user.community.objId, tempValue, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.userList.items.forEach(function (elem) {
                            if (elem.objId == user.objId) {
                                elem.authenticationStatus = tempValue.authenticationStatus;
                            }
                        });
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        }

        /**
         * 升级为达人，或者取消达人
         * @param user
         * @param messageTitle
         * @param type
         */
        $scope.setOrCancelTalent = function (user, messageTitle, type) {
            if (type == '1') {
                bootbox.prompt(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/' + result + '/' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            } else {
                bootbox.confirm(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/ /' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            }
        }

        /**
         * 保存黑白操作设置
         * @param userObjId
         * @param toBeBlackListUserFrozen
         * @param reason
         */
        $scope.saveBlackListOrWhiteList = function (userObjId, toBeBlackListUserFrozen, reason) {
            if (toBeBlackListUserFrozen == true) {
                var tempFrozenReason = {
                    frozenOrNot: true,
                    reason: reason
                }
                if (reason == null || reason == '') {
                    return;
                }
            } else {
                var tempFrozenReason = {
                    frozenOrNot: false,
                    reason: reason
                }
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/putFrontendUserToBlackList/' + userObjId, tempFrozenReason, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#user_modal').modal('hide');
                $scope.userList.items.forEach(function (elem) {
                    if (elem.objId == userObjId) {
                        elem.frozenOrNot = tempFrozenReason.frozenOrNot;
                        elem.reason = tempFrozenReason.reason;
                    }
                });
            }).error(function () {
            });
        }
    }]).directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };

            }
        };
    });



